<template>
  <div id="picture-detail-page">
    <a-row :gutter="[24, 24]" justify="center">
      <!-- 图片展示区 -->
      <a-col :sm="24" :md="16" :xl="18">
        <a-card title="图片预览" class="preview-card">
          <a-image
            :src="picture.url"
            :preview="{ visible: previewVisible, onVisibleChange: (val) => (previewVisible = val) }"
            @click="previewVisible = true"
            class="picture-image"
          />
        </a-card>
      </a-col>

      <!-- 图片信息区 -->
      <a-col :sm="24" :md="8" :xl="6">
        <a-card title="图片信息" class="info-card">
          <a-descriptions :column="1" size="middle">
            <a-descriptions-item label="作者">
              <a-space>
                <a-avatar :size="40" :src="picture.user?.userAvatar" />
                <span class="author-name">{{ picture.user?.userName }}</span>
              </a-space>
            </a-descriptions-item>
            <a-descriptions-item label="名称">
              <span class="text-highlight">{{ picture.name ?? '未命名' }}</span>
            </a-descriptions-item>
            <a-descriptions-item label="简介">{{
              picture.introduction ?? '-'
            }}</a-descriptions-item>
            <a-descriptions-item label="分类">
              <a-tag color="blue">{{ picture.category ?? '默认' }}</a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="标签">
              <a-tag v-for="tag in picture.tags" :key="tag" color="geekblue">
                {{ tag }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="格式">{{ picture.picFormat ?? '-' }}</a-descriptions-item>
            <a-descriptions-item label="尺寸">
              {{ picture.picWidth ?? '-' }} × {{ picture.picHeight ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="宽高比">{{ picture.picScale ?? '-' }}</a-descriptions-item>
            <a-descriptions-item label="大小">{{
              formatSize(picture.picSize)
            }}</a-descriptions-item>
            <a-descriptions-item label="主色调">
              <a-space>
                {{ picture.picColor ?? '-' }}
                <div
                  v-if="picture.picColor"
                  :style="{
                    backgroundColor: toHexColor(picture.picColor),
                    width: '16px',
                    height: '16px',
                  }"
                />
              </a-space>
            </a-descriptions-item>
          </a-descriptions>

          <a-divider />

          <a-space wrap align="center" style="width: 100%; justify-content: center">
            <a-button type="primary" @click="doDownload">
              <DownloadOutlined />
              免费下载
            </a-button>
            <a-button type="dashed" size="small" @click="(e) => doShare(picture, e)">
              <ShareAltOutlined />
              图片分享
            </a-button>
            <a-button v-if="canEdit" type="default" @click="doEdit">
              <EditOutlined />
              编辑
            </a-button>
            <a-button v-if="canDelete" danger @click="doDelete">
              <DeleteOutlined />
              删除
            </a-button>
          </a-space>
        </a-card>
      </a-col>
    </a-row>
    <ShareModal ref="shareModalRef" :link="shareLink" />
  </div>
</template>

<script setup lang="ts">
import { computed, createVNode, onMounted, ref } from 'vue'
import { deletePictureUsingPost, getPictureVoByIdUsingGet } from '@/api/pictureController.ts'
import { message, Modal } from 'ant-design-vue'
import { downloadImage, formatSize, toHexColor } from '../utils'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import router from '@/router'
import {
  EditOutlined,
  DeleteOutlined,
  DownloadOutlined,
  ExclamationCircleOutlined, ShareAltOutlined
} from '@ant-design/icons-vue'
import ShareModal from '@/components/ShareModal.vue'
import { SPACE_PERMISSION_ENUM } from '@/constants/space.ts'

// 通用权限检查函数
function createPermissionChecker(permission: string) {
  return computed(() => {
    return (picture.value.permissionList ?? []).includes(permission)
  })
}

// 定义权限检查
const canEdit = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_EDIT)
const canDelete = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_DELETE)


// 分享弹窗引用
const shareModalRef = ref()
// 分享链接
const shareLink = ref<string>()

// 分享
const doShare = () => {
  shareLink.value = `${window.location.protocol}//${window.location.host}/picture/${picture.value.id}`
  if (shareModalRef.value) {
    shareModalRef.value.openModal()
  }
}


const props = defineProps<{ id: string | number }>()

const picture = ref<API.PictureVO>({})
const previewVisible = ref(false)

// 获取图片详情
const fetchPictureDetail = async () => {
  try {
    const res = await getPictureVoByIdUsingGet({ id: props.id })
    if (res.data.code === 0 && res.data.data) {
      picture.value = res.data.data
    } else {
      message.error('获取图片详情失败，' + res.data.message)
    }
  } catch (e: any) {
    message.error('获取图片详情失败：' + e.message)
  }
}

onMounted(() => {
  fetchPictureDetail()
})

const loginUserStore = useLoginUserStore()

// 编辑
const doEdit = () => {
  router.push({
    path: '/add_picture',
    query: {
      id: picture.value.id,
      spaceId: picture.value.spaceId,
    },
  })
}

const doDelete = async () => {
  if (!picture.value?.id) return

  Modal.confirm({
    title: '⚠️ 确定要删除这张图片吗？',
    content: '删除后无法恢复，请谨慎操作！',
    icon: createVNode(ExclamationCircleOutlined, { style: 'color: red' }),
    centered: true,
    maskClosable: false,
    okText: '删除',
    okType: 'danger',
    cancelText: '取消',
    cancelButtonProps: {
      style: { backgroundColor: '#f5f5f5', borderColor: '#d9d9d9', color: '#333' },
    },
    okButtonProps: {
      style: { backgroundColor: '#ff4d4f', borderColor: '#ff4d4f', color: '#fff' },
    },
    async onOk() {
      try {
        const res = await deletePictureUsingPost({ id: picture.value.id })
        if (res.data.code === 0) {
          message.success('✅ 删除成功')

          // 清除图片数据
          picture.value = null

          // 500ms 后跳转到主页
          setTimeout(() => {
            router.push('/')
          }, 500)
        } else {
          message.error('❌ 删除失败')
        }
      } catch (error) {
        message.error('❌ 删除出错，请稍后重试')
        console.error('删除图片出错:', error)
      }
    },
  })
}

const doDownload = () => downloadImage(picture.value.url)
</script>

<style scoped>
/* 页面整体美化 */
#picture-detail-page {
  padding: 32px;
  background: linear-gradient(to right top, #e3f2fd, #bbdefb, #90caf9, #64b5f6, #42a5f5);
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 预览卡片样式 */
.preview-card {
  border-radius: 16px;
  box-shadow: 0 6px 25px rgba(0, 0, 0, 0.12);
  overflow: hidden;
  background: white;
  padding: 20px;
}

/* 图片预览 */
.picture-image {
  max-height: 650px;
  width: 100%;
  object-fit: cover; /* 适应不同图片比例，减少空白 */
  border-radius: 12px;
  transition:
    transform 0.3s ease-in-out,
    box-shadow 0.3s ease-in-out;
}

.picture-image:hover {
  transform: scale(1.05);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
  cursor: pointer;
}

/* 信息卡片：玻璃拟态风格 */
.info-card {
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(15px);
  border-radius: 16px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
  padding: 24px;
}

/* 头像 & 作者名字 */
.author-name {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  letter-spacing: 0.5px;
}

/* 文字高亮 */
.text-highlight {
  font-size: 20px;
  font-weight: bold;
  color: #1976d2;
  letter-spacing: 0.5px;
}

:deep(.ant-btn-primary) {
  background: linear-gradient(to right, #42a5f5, #1976d2);
  border: none;
  color: white;
}

:deep(.ant-btn-primary:hover) {
  background: linear-gradient(to right, #64b5f6, #1e88e5);
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
}

:deep(.ant-btn-dangerous) {
  background: linear-gradient(to right, #f44336, #d32f2f);
  border: none;
  color: white;
}

:deep(.ant-btn-dangerous:hover) {
  background: linear-gradient(to right, #e57373, #c62828);
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
}
</style>
